import React, { useState, useEffect } from 'react';
import { View, ScrollView, PullToRefresh } from '@tarojs/components';
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import { Toast, Empty } from '@nutui/nutui-react-taro';
import Card, { CardProps } from './components/Card';
import { getPosts } from '../../services/post';
import './index.scss';

export default function Index() {
  const [cardList, setCardList] = useState<CardProps[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 获取文章列表数据
  const fetchPostList = async (params: { page: number; pageSize: number }, isRefresh = false) => {
    try {
      setLoading(true);
      const response = await getPosts(params);
      
      // 处理数据转换
      const posts = response.list.map(post => ({
        id: post.id,
        title: post.title,
        author: post.author.nickname,
        time: formatTimeAgo(post.createdAt),
        avatar: post.author.avatar,
        content: post.content,
        image: post.images?.[0],
        comment: post.commentCount,
        like: post.likeCount
      }));
      
      // 如果是刷新，则替换数据，否则追加数据
      if (isRefresh) {
        setCardList(posts);
      } else {
        setCardList(prev => [...prev, ...posts]);
      }
      
      // 更新是否有更多数据
      setHasMore(response.hasMore);
      return response;
    } catch (error) {
      setToastMessage(error.message || '获取数据失败');
      setShowToast(true);
      return null;
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchPostList({ page, pageSize });
  }, []);

  // 处理下拉刷新
  usePullDownRefresh(async () => {
    setRefreshing(true);
    setPage(1);
    await fetchPostList({ page: 1, pageSize }, true);
    Taro.stopPullDownRefresh();
  });

  // 处理触底加载更多
  useReachBottom(async () => {
    if (hasMore && !loading) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchPostList({ page: nextPage, pageSize });
    }
  });

  // 格式化时间
  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    
    if (diffSeconds < 60) {
      return `${diffSeconds}秒前`;
    }
    
    const diffMinutes = Math.floor(diffSeconds / 60);
    if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    }
    
    const diffHours = Math.floor(diffMinutes / 60);
    if (diffHours < 24) {
      return `${diffHours}小时前`;
    }
    
    const diffDays = Math.floor(diffHours / 24);
    if (diffDays < 30) {
      return `${diffDays}天前`;
    }
    
    const diffMonths = Math.floor(diffDays / 30);
    if (diffMonths < 12) {
      return `${diffMonths}月前`;
    }
    
    return `${Math.floor(diffMonths / 12)}年前`;
  };

  const handleClick = (item: CardProps) => {
    Taro.navigateTo({
      url: `/pages/detail/index?id=${item.id}`,
      success: () => {
        console.log('跳转成功');
      },
      fail: () => {
        console.log('跳转失败');
      }
    });
  };

  return (
    <View className="index-container">
      <ScrollView 
        className="wrapper" 
        scrollY
        lowerThreshold={100}
      >
        {cardList.length > 0 ? (
          cardList.map((item) => (
            <Card 
              key={item.id} 
              {...item} 
              onClick={() => handleClick(item)}
            />
          ))
        ) : (
          <Empty description="暂无内容" />
        )}
        
        {loading && !refreshing && (
          <View className="loading-more">加载中...</View>
        )}
        
        {!hasMore && cardList.length > 0 && (
          <View className="no-more">没有更多内容了</View>
        )}
      </ScrollView>
      
      <Toast
        visible={showToast}
        content={toastMessage}
        onClose={() => setShowToast(false)}
        type="warn"
        duration={2000}
      />
    </View>
  );
}
